<template>
  <div class="monitoring-dashboard">
    <a-row :gutter="[16, 16]">
      <!-- Server Status -->
      <a-col :span="24">
        <a-card title="服务器状态监控" :loading="loading.server">
          <a-row :gutter="[16, 16]">
            <a-col :span="6" v-for="metric in serverMetrics" :key="metric.name">
              <a-statistic
                :title="metric.name"
                :value="metric.value"
                :precision="metric.precision"
                :suffix="metric.suffix"
                :valueStyle="{ color: getMetricColor(metric.value, metric.threshold) }"
              />
            </a-col>
          </a-row>
          <div ref="serverChart" style="height: 300px; margin-top: 20px"></div>
        </a-card>
      </a-col>

      <!-- User Behavior -->
      <a-col :span="12">
        <a-card title="实时用户行为" :loading="loading.behavior">
          <div ref="behaviorChart" style="height: 300px"></div>
        </a-card>
      </a-col>

      <!-- Error Monitoring -->
      <a-col :span="12">
        <a-card title="错误监控" :loading="loading.errors">
          <div ref="errorChart" style="height: 300px"></div>
        </a-card>
      </a-col>

      <!-- Alerts -->
      <a-col :span="24">
        <a-card title="系统警报">
          <template #extra>
            <a-radio-group v-model:value="alertFilter" button-style="solid">
              <a-radio-button value="all">全部</a-radio-button>
              <a-radio-button value="error">错误</a-radio-button>
              <a-radio-button value="warning">警告</a-radio-button>
            </a-radio-group>
          </template>
          
          <a-table
            :columns="alertColumns"
            :data-source="filteredAlerts"
            :pagination="{ pageSize: 10 }"
            :loading="loading.alerts"
          >
            <template #bodyCell="{ column, record }">
              <template v-if="column.key === 'level'">
                <a-tag :color="record.level === 'error' ? 'red' : 'orange'">
                  {{ record.level === 'error' ? '错误' : '警告' }}
                </a-tag>
              </template>
              <template v-else-if="column.key === 'action'">
                <a-space>
                  <a @click="handleAlertAction(record, 'resolve')">处理</a>
                  <a @click="handleAlertAction(record, 'ignore')">忽略</a>
                </a-space>
              </template>
            </template>
          </a-table>
        </a-card>
      </a-col>
    </a-row>
  </div>
</template>

<script>
import { defineComponent, ref, onMounted, computed } from 'vue'
import * as echarts from 'echarts'
import { getServerStatus, getUserBehavior, getSystemAlerts, handleAlert } from '@/api/analytics'

export default defineComponent({
  name: 'MonitoringDashboard',
  setup() {
    const loading = ref({
      server: true,
      behavior: true,
      errors: true,
      alerts: true
    })

    const serverMetrics = ref([
      { name: 'CPU使用率', value: 0, suffix: '%', threshold: 80, precision: 1 },
      { name: '内存使用率', value: 0, suffix: '%', threshold: 80, precision: 1 },
      { name: '磁盘使用率', value: 0, suffix: '%', threshold: 80, precision: 1 },
      { name: '网络延迟', value: 0, suffix: 'ms', threshold: 1000, precision: 0 }
    ])

    const alerts = ref([])
    const alertFilter = ref('all')
    
    const alertColumns = [
      {
        title: '级别',
        dataIndex: 'level',
        key: 'level',
        width: 100
      },
      {
        title: '时间',
        dataIndex: 'time',
        key: 'time',
        width: 180
      },
      {
        title: '消息',
        dataIndex: 'message',
        key: 'message'
      },
      {
        title: '操作',
        key: 'action',
        width: 150
      }
    ]

    const filteredAlerts = computed(() => {
      if (alertFilter.value === 'all') return alerts.value
      return alerts.value.filter(alert => alert.level === alertFilter.value)
    })

    const getMetricColor = (value, threshold) => {
      return value >= threshold ? '#f5222d' : '#52c41a'
    }

    const handleAlertAction = async (alert, action) => {
      try {
        await handleAlert(alert.id, action)
        // 重新加载警报列表
        fetchAlerts()
      } catch (error) {
        console.error('Failed to handle alert:', error)
      }
    }

    const fetchServerStatus = async () => {
      try {
        const response = await getServerStatus()
        serverMetrics.value = response.data.metrics
        updateServerChart(response.data.history)
      } finally {
        loading.value.server = false
      }
    }

    const fetchAlerts = async () => {
      try {
        const response = await getSystemAlerts()
        alerts.value = response.data
      } finally {
        loading.value.alerts = false
      }
    }

    // 初始化图表
    let serverChart = null
    let behaviorChart = null
    let errorChart = null

    onMounted(() => {
      // 初始化服务器状态图表
      serverChart = echarts.init(document.querySelector('#serverChart'))
      behaviorChart = echarts.init(document.querySelector('#behaviorChart'))
      errorChart = echarts.init(document.querySelector('#errorChart'))

      // 加载数据
      fetchServerStatus()
      fetchAlerts()

      // 设置定时刷新
      const timer = setInterval(() => {
        fetchServerStatus()
        fetchAlerts()
      }, 60000) // 每分钟刷新一次

      // 组件卸载时清理
      onUnmounted(() => {
        clearInterval(timer)
        serverChart.dispose()
        behaviorChart.dispose()
        errorChart.dispose()
      })
    })

    return {
      loading,
      serverMetrics,
      alerts,
      alertFilter,
      alertColumns,
      filteredAlerts,
      getMetricColor,
      handleAlertAction
    }
  }
})
</script>

<style scoped>
.monitoring-dashboard {
  padding: 24px;
}
</style> 